package com.cfpl.project_common.util;

import cn.hutool.core.date.DateUtil;
import com.cfpl.project_common.enums.CodeEnum;
import com.cfpl.project_common.exception.BusException;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;

/**
 * @Auther: LYP
 * @Date: 2023/11/23 - 10:32
 * @Description: com.cfpl.project_common.util
 * @version: 1.0
 */
public class FileUtils {


    public static boolean checkPathExisted(File file) {
        if (!(file.exists() && file.isDirectory())){
            //创建用户头像目录
            try {
                file.mkdirs();
            } catch (Exception e) {
                throw new BusException(CodeEnum.SYSTEM_ERROR);
            }
        }
        return file.exists();
    }

    /**
     *
     * @param path       路径
     * @param bytes     文件字节码
     * @param objectID  目标标识
     */
    public static String uploadPictureFile(String path,byte[] bytes,Long objectID){
        String filename = path + DateUtil.format(new Date(),"yyyyMMddHHmmss")+objectID+".jpg";
        try (
                FileOutputStream fos = new FileOutputStream(filename);
                BufferedOutputStream bos = new BufferedOutputStream(fos)
        ){
            bos.write(bytes);
            bos.flush();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return filename;
    }
}
